﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using DAL;
using Newtonsoft.Json;
using System.Web.UI.HtmlControls;

namespace PeisongWeb.admin
{
    public partial class orderEdit : adminPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (hasPermission("DB", 2))
                {
                    drpCompanyBind();
                }
                else
                {
                    Library.Script.ClientMsgUrl("没有权限！", "index.aspx");
                    return;
                }
               
            }
        }
        /// <summary>
        /// 绑定所有采购商
        /// </summary>
        private void drpCompanyBind()
        {
            DataTable dt = logic.company.listWithCompanyType("2");
            drp_company.DataSource = dt;
            drp_company.DataBind();
            drp_company.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--请选择--", ""));

            ext_receiveDt.SelectedDate = DateTime.Now.AddDays(1);

            ddl_receiveTime.DataSource = logic.sysCode.receiveTime();
            ddl_receiveTime.DataBind();
            //ddl_receiveTime.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--请选择送货时间--", ""));
        }

        protected void lbn_AddProduct_Click(object sender, EventArgs e)
        {
            int companyId = Convert.ToInt32(drp_company.SelectedValue);
            // 固定价格商品信息
             CompanyEntity companyEntity = logic.company.getById(companyId);
             if (companyEntity.EnabledWeeklyPrice)
             {
                 DateTime receiveDt = ext_receiveDt.SelectedDate;
                 DataTable dt = logic.buyerFixedPricePeriodItem.listByBuyerIdAndReceiveDt(companyId, receiveDt);
                 if (dt.Rows.Count!=0)
                 {
                     rpt_bfpProduct.DataSource = dt;
                     rpt_bfpProduct.DataBind();
                     ViewState["start"] = dt.Rows[0]["startTime"].ToString();
                     ViewState["end"] = dt.Rows[0]["endTime"].ToString();
                     bfpProduct_add.Show();
                     lit_bfpTitle.Text = drp_company.SelectedItem.Text + "<font color='red'>" + receiveDt.ToShortDateString() + "</font>" + "  配送的商品价格如下：";
                 }
                 else
                 {
                     Library.Script.ClientMsg("此企业为固定价企业，未设置购买价格！");
                 }
             }
             else
             {
                 categoryRootBind();
                 categorySubBind();
                 rptProBind();
                 win_product.Show();
             }
        }

        protected void drp_company_SelectedIndexChanged(object sender, EventArgs e)
        {
            hd_proScope.Value = "";
            if (drp_company.SelectedValue.Trim() != "")
            {
                DataSet ds = logic.company.select("companyid=" + drp_company.SelectedValue.Trim(), "companyid", 1, 1);
                DataRow dr = ds.Tables[1].Rows[0];
                lbl_contact.Text = dr["contact"].ToString();
                lbl_Address.Text = dr["area"].ToString() + dr["address"].ToString();
                lbl_contactMobile.Text = dr["mobile"].ToString();
                lbl_contactPhone.Text = dr["Phone"].ToString();
                hdCompanyNature.Value = dr["businessNature"].ToString();
            }
            else
            {
                lbl_contact.Text = "请选择公司";
                lbl_Address.Text = "请选择公司";
                lbl_contactMobile.Text = "请选择公司";
                lbl_contactPhone.Text = "";
            }
        }
        protected void lbn_search_Click(object sender, EventArgs e)
        {
            AspNetPager2.CurrentPageIndex = 1;
            rptProBind();
        }

        /// <summary>
        /// 绑定在采购商的采购范围里的所有商品
        /// </summary>
        void rptProBind()
        {
            int companyId = Convert.ToInt32(drp_company.SelectedValue);
            StringBuilder where = new StringBuilder();
            where.AppendFormat("companyId ={0} and categoryIsShow=1", companyId);

            if (ddl_CategorySub.SelectedValue != "")
                where.AppendFormat("and categoryId={0}", ddl_CategorySub.SelectedValue);
            if (txt_ProductNo.Text.Trim() != "")
                where.AppendFormat(" and productNo='{0}'", txt_ProductNo.Text.Trim());
            if (txt_ProductName.Text.Trim() != "")
                where.AppendFormat(" and [Name] LIKE '%{0}%'", txt_ProductName.Text.Trim());

            //DataSet ds = logic.buyerRange.listWithPrice(where.ToString(), "productId", AspNetPager2.PageSize, AspNetPager2.CurrentPageIndex);
            DataSet ds = logic.product.listWithCurrentPriceAdmin(where.ToString(),"productId",AspNetPager2.PageSize,AspNetPager2.CurrentPageIndex);
            AspNetPager2.RecordCount = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
            rpt_Products.DataSource = ds.Tables[1];
            rpt_Products.DataBind();
        }
        protected void AspNetPager2_PageChanged(object sender, EventArgs e)
        {
            rptProBind();
        }
        void categoryRootBind()
        {
            //当采购商不等于空的时候，绑定在采购商的采购范围的大类
            if (drp_company.SelectedValue!="")
            {
                int companyId = Convert.ToInt32(drp_company.SelectedValue);
                //ddl_CategoryRoot.DataSource = logic.category.listWithCompanyRange(companyId);
                //ddl_CategoryRoot.DataSource = logic.buyerRange.rootCategorylistWithCompanyRange(companyId);
                ddl_CategoryRoot.DataSource = logic.category.getByParent(0);
                ddl_CategoryRoot.DataBind();
                ddl_CategoryRoot.Items.Insert(0,new ListItem("-所有大类-",""));
            }
            else
            {
                ddl_CategoryRoot.DataBind();
            }
        }

        void categorySubBind()
        {
            //当大类不等于空的时候，就绑定小类
            if (ddl_CategoryRoot.SelectedValue != "")
            {
                int companyId = Convert.ToInt32(drp_company.SelectedValue);
                //DataTable dt = logic.category.getByParent(Convert.ToInt32(ddl_CategoryRoot.SelectedValue));
                //DataTable dt = logic.buyerRange.subCategory_listWithCompanyRange(companyId, Convert.ToInt32(ddl_CategoryRoot.SelectedValue));
                DataTable dt = logic.category.getByParent(Convert.ToInt32(ddl_CategoryRoot.SelectedValue));
                ddl_CategorySub.DataSource = dt;
                ddl_CategorySub.DataBind();
                ddl_CategorySub.Items.Insert(0, new ListItem("-请选择小类-", ""));
            }
            else
            {
                ddl_CategorySub.Items.Clear();
            }
        }
        protected void ddl_CategoryRoot_SelectedIndexChanged(object sender, EventArgs e)
        {
            categorySubBind();
        }

        protected void ddl_CategorySub_SelectedIndexChanged(object sender, EventArgs e)
        {
            AspNetPager2.CurrentPageIndex = 1;
            rptProBind();
        }

        protected void btn_Save_Click(object sender, EventArgs e)
        {
            DateTime start=Convert.ToDateTime(ViewState["start"]);
            DateTime end =Convert.ToDateTime(ViewState["end"]);
            int companyId = Convert.ToInt32(drp_company.SelectedValue);
            bool isfpPrice = logic.company.getById(companyId).EnabledWeeklyPrice;
            //收货日期在价格周期中添加订单，否则日期选错，商品重新添加
            if ( isfpPrice==true)
            {
                if (ext_receiveDt.SelectedDate <= start || ext_receiveDt.SelectedDate >= end)
                {
                    Library.Script.ClientMsg("对不起，此收货日期的商品价格不对，你确认【收货日期】是否正确，确认收货日期之后再重新添加商品！");
                    return;
                }
            }

            // 日志记录
            log4net.ILog logger = log4net.LogManager.GetLogger("ApplicationFileAppender");//读取log4net的配置文件
            logger.Info("电话订单信息：" + hd_proScope.Value);

            // 订单细目
            List<OrderItemEntity> orderItems = JsonConvert.DeserializeObject<List<OrderItemEntity>>(hd_proScope.Value);

            if (orderItems.Count > 0)
            {
                // 计算订单总价
                decimal serverTotalAmount = 0m;
                orderItems.ForEach(x => serverTotalAmount += x.Quantity * x.Price);
                serverTotalAmount = Math.Round(serverTotalAmount, 2, MidpointRounding.AwayFromZero);

                int companyid = Convert.ToInt32(drp_company.SelectedValue);
                OrderEntity od = new OrderEntity();
                od.Amount = serverTotalAmount;    //支付总价
                od.CompanyId = companyid;                               //采购商ID
                od.StandardAmount = od.Amount;                          //汇总总价
                od.CustomerId = logic.sysAdmin.AdminID;                 //用户ID，电话订单就代表录入者ID
                od.FireightFee = Convert.ToDecimal(txt_fireightFee.Value);  //运费
                od.Note = txt_Note.Text;                                     //备注
                od.OrderNo = ""; //传空值，存储过程自动得到订单编号
                od.Source = "2";    //订单来源：1、网站订单；2、电话订单
                od.Taxfee = Convert.ToDecimal(txt_taxfee.Value); //税费
                od.Status = "1";  //订单状态：“1”：已提交；“2”备货中；“3”已发货；“4”交易成功；“5”交易关闭；
                //string time = ddl_receiveTime.SelectedValue.Substring(ddl_receiveTime.SelectedValue.IndexOf("-") + 1, ddl_receiveTime.SelectedValue.Length - (ddl_receiveTime.SelectedValue.IndexOf("-") + 1));
                //od.ReceiveDt = Convert.ToDateTime(ext_receiveDt.Value).AddHours(Convert.ToInt32(time.Substring(0,time.IndexOf(":"))));    //收货时间

                string timeRange = ddl_receiveTime.SelectedItem.Text;
                int hour = Convert.ToInt32(timeRange.Substring(timeRange.IndexOf("-") + 1, timeRange.Length - (timeRange.IndexOf("-") + 4)));
                od.ReceiveDt = Convert.ToDateTime(ext_receiveDt.Value).AddHours(hour);    //收货时间

                od.TypeCount = orderItems.Count;
                TimeSpan ts = Convert.ToDateTime(ext_receiveDt.SelectedDate.ToShortDateString()) - DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd"));
                int day = ts.Days;
                if (day > 1 && isfpPrice == false)
                {
                    od.Status = "6";
                    int orderid = logic.order.insertDynamicOrder(od);
                    foreach (OrderItemEntity orderItem in orderItems)
                    {
                        orderItem.CustomerId = logic.sysAdmin.AdminID;
                        orderItem.OrderId = orderid;
                        orderItem.InitQuantity = orderItem.Quantity;
                        PriceEntity pr = logic.price.getByProduct(orderItem.ProductId, orderItem.BusinessNature);
                        orderItem.SellerId = pr.CompanyId;                //供应商ID
                        orderItem.SellerPrice = pr.SellerPrice;           //供应价格

                        logic.orderItem.insertDynamicOrderItem(orderItem);
                    }
                }
                else
                {
                    int orderid = logic.order.insert(od);

                    foreach (OrderItemEntity orderItem in orderItems)
                    {
                        orderItem.CustomerId = logic.sysAdmin.AdminID;
                        orderItem.OrderId = orderid;
                        orderItem.InitQuantity = orderItem.Quantity;
                        PriceEntity pr = logic.price.getByProduct(orderItem.ProductId, orderItem.BusinessNature);
                        orderItem.SellerId = pr.CompanyId;                //供应商ID
                        orderItem.SellerPrice = pr.SellerPrice;           //供应价格

                        logic.orderItem.insert(orderItem);
                    }
                }
                Library.Script.ClientMsgUrl("订单保存成功!", "orderList.aspx");
            }
            else
            {
                Library.Script.ClientMsg("订单数据无效！");
                return;
            }

        }
    }
}
